package com.heatup.apt.common.util;

import com.google.common.base.Preconditions;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
public class FileUtil {

    public final static String TARGET_DIR = "headImg";
    public final static String TARGET_DIR_TEMP = "tempImg";

    /**
     * 获取新的文件名
     *
     * @param fileName
     * @return
     */
    public static String getNewFileName(String fileName) {
        Preconditions.checkNotNull(fileName);
        String extFile = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        return String.valueOf(System.currentTimeMillis()) + extFile;
    }
    /**
     * 获取零时/非零时新的文件名
     *
     * @param fileName
     * @param type 0:非零时文件 1:零时文件
     * @return
     */
    public static String getNewFileNameType(String fileName,int type) {
        Preconditions.checkNotNull(fileName);
        String temp ="";
        if(type != 0){
            temp ="_coach";
        }
        String extFile = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        return String.valueOf(System.currentTimeMillis()) +temp+ extFile;
    }
    /**
     * 获取扩展名
     *
     * @param fileName
     * @return
     */
    public static String getExtFileName(String fileName) {
        Preconditions.checkNotNull(fileName);
        String extFile = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        return extFile;
    }

    /**
     * 保存图片
     *
     * @param file
     * @return
     */
    public static String saveFileUtil(MultipartFile file) {
        if (file == null || file.isEmpty()) return null;
        String oldName = file.getOriginalFilename();
        String newFileName = getNewFileName(oldName);
        String extFileName = getExtFileName(oldName);
        File Dir = new File(TARGET_DIR);
        if (!Dir.exists()) {
            Dir.mkdirs();
        }

        try {
            File photoFile = new File(TARGET_DIR, newFileName);
            file.transferTo(photoFile);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return newFileName;
    }

    /**
     * 上传临时图片
     *
     * @param file
     * @return
     */
    public static String uploadFileUtil(MultipartFile file,String sysPath) {
        if (file == null || file.isEmpty()) return null;
        String oldName = file.getOriginalFilename();
        String newFileName = getNewFileName(oldName);
        File Dir = new File(sysPath+File.separator+TARGET_DIR_TEMP);
        if (!Dir.exists()) {
            Dir.mkdirs();
        }
        try {
            File photoFile = new File(sysPath+File.separator+TARGET_DIR_TEMP, newFileName);
            file.transferTo(photoFile);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return newFileName;
    }

    /**
     * 把临时图片移动到文件保存目录
     */
    public static String mvFile(String  oldFileName,String path) {
        File Dir = new File(path+File.separator+TARGET_DIR_TEMP);
        if (!Dir.exists()) {
            Dir.mkdirs();
        }
        Dir = new File(path+File.separator+TARGET_DIR);
        if (!Dir.exists()) {
            Dir.mkdirs();
        }
        String oldFilePath = new File(path+File.separator+TARGET_DIR_TEMP, oldFileName).getAbsolutePath();
        String newFilePath = new File(path+File.separator+TARGET_DIR, oldFileName).getAbsolutePath();
        moveFile(oldFilePath,newFilePath);
        return TARGET_DIR+"/"+oldFileName;
    }

    /**
     * 删除上传图片
     * type
     */
    public static void delFile(String  fileName, String path) {
        //1.删除临时文件夹里的图片
        delFile(path+File.separator+TARGET_DIR_TEMP+File.separator+fileName);
        //2.删除图片文件夹里的图片
        delFile(path+File.separator+TARGET_DIR+File.separator+fileName);
    }
    /**
     *  移动文件到指定目录
     *  @param  oldPath  String  如：c:/fqf.txt
     *  @param  newPath  String  如：d:/fqf.txt
     */
    public  static void  moveFile(String  oldPath,  String  newPath)  {
        copyFile(oldPath,  newPath);
        delFile(oldPath);

    }

    /**
     *  删除文件
     *  @return  boolean
     */
    public  static void  delFile(String  filePathAndName)  {
        try  {
            String  filePath  =  filePathAndName;
            filePath  =  filePath.toString();
            java.io.File  myDelFile  =  new  java.io.File(filePath);
            myDelFile.delete();
        }
        catch  (Exception  e)  {
            System.out.println("删除文件操作出错");
            e.printStackTrace();

        }
    }

    /**
     *  复制单个文件
     *  @param  oldPath  String  原文件路径  如：c:/fqf.txt
     *  @param  newPath  String  复制后路径  如：f:/fqf.txt
     *  @return  boolean
     */
    public static void  copyFile(String  oldPath,  String  newPath)  {
        try  {
            int  byteread  =  0;
            File  oldfile  =  new  File(oldPath);
            if  (oldfile.exists())  {  //文件存在时
                InputStream inStream  =  new FileInputStream(oldPath);  //读入原文件
                FileOutputStream fs  =  new  FileOutputStream(newPath);
                byte[]  buffer  =  new  byte[1024];
                while  (  (byteread  =  inStream.read(buffer))  !=  -1)  {
                    fs.write(buffer,  0,  byteread);
                }
                inStream.close();
            }
        }
        catch  (Exception  e)  {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();

        }
    }

    /**
     *  删除文件夹
     *  @return  boolean
     */
    public  static void  delFolder(String  folderPath)  {
        try  {
            delAllFile(folderPath);  //删除完里面所有内容
            String  filePath  =  folderPath;
            filePath  =  filePath.toString();
            java.io.File  myFilePath  =  new  java.io.File(filePath);
            myFilePath.delete();  //删除空文件夹

        }
        catch  (Exception  e)  {
            System.out.println("删除文件夹操作出错");
            e.printStackTrace();

        }
    }
    /**
     *  删除文件夹里面的所有文件
     *  @param  path  String  文件夹路径  如  c:/fqf
     */
    public  static void  delAllFile(String  path)  {
        File  file  =  new  File(path);
        if  (!file.exists())  {
            return;
        }
        if  (!file.isDirectory())  {
            return;
        }
        String[]  tempList  =  file.list();
        File  temp  =  null;
        for  (int  i  =  0;  i  <  tempList.length;  i++)  {
            if  (path.endsWith(File.separator))  {
                temp  =  new  File(path  +  tempList[i]);
            }
            else  {
                temp  =  new  File(path  +  File.separator  +  tempList[i]);
            }
            if  (temp.isFile())  {
                temp.delete();
            }
            if  (temp.isDirectory())  {
                delAllFile(path+"/"+  tempList[i]);//先删除文件夹里面的文件
                delFolder(path+"/"+  tempList[i]);//再删除空文件夹
            }
        }
    }
}
